<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/12
 * Time: 18:16
 */

namespace Modules\Api\Service;

use HiCommon\Repository\FeedbackRepository;
use HiCommon\Repository\ProtocolRepository;
use HiCommon\Repository\CollectRepository;
use HiCommon\Repository\UserInviteSetRepository;
use HiCommon\Repository\UserInviteRepository;
use HiCommon\Repository\BannerRepository;
use HiCommon\Repository\RoadRescueRepository;
use HiCommon\Repository\GiftRepository;
use HiCommon\Repository\CouponGrantDetailRepository;


class FeedbackService extends BaseService
{

    /**
     *  添加意见反馈
     *  hinq 2019 11 13
     *
     **/
    public function store( array $arrInput ){
        try{
            $user_id = api_user_id();
            if( empty( $arrInput['content'] ) ){
                return ['state'=> 1,'msg'=>'反馈信息不能为空','data'=>[],'error'=>''];
            }
            //如果填写了联系方式 就验证联系方式  联系方式手机号或邮箱
            if( !empty( $arrInput['contact'] ) && !preg_match("/^1[23456789]{1}\d{9}$/",$arrInput['contact']) && !preg_match('/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i',$arrInput['contact']) ){
                return ['state'=> 1,'msg'=>'联系方式不正确','data'=>[],'error'=>''];
            }
            if( isset( $arrInput['imgs']) ) { //图片最大只能上传3张
                if (!(count($arrInput['imgs']) <= 3)) {
                    return ['state' => 1, 'msg' => '最多只能上传3张图片', 'data' => [], 'error' => ''];
                }
                if (count($arrInput['imgs']) > 0 && count($arrInput['imgs']) <= 3) {
                    $imgs = implode(',', $arrInput['imgs']);
                    $arrInput['imgs'] = $imgs;
                }
            }
            $arrInput['user_id'] = $user_id;
            $arrInput['state'] = 1;
            $res = FeedbackRepository::add_one( (array) $arrInput );
            if (empty( $res ) ) {
                return hello_error('反馈失败');
            }
            return hello_success('ok');
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取用户协议列表
     *  hinq 2019 11 13
     *
     **/
        public function protocol_list(){
        try{
            //type
            //1：隐私政策
            //2：用户协议
            //3：门店加盟
            //4：关于信达（用户端）
            //5：免责说明
            //6：商家服务协议
            //7：道路救援服务协议
            //8：帮助中心
            //9：Vip升级说明
            //10：小程序免责说明
            //11：商户入驻说明
            //12：商户签订协议
            $arr_option['where'] = ['type'=>2,'status'=>1];
            $arr_option['order'] = ['key'=>'sort','value'=>'asc'];
            $arr_option['field'] = ['id','title','content'];
            $arr_list = ProtocolRepository::get_all( (array) $arr_option )->toarray();
            if( !$arr_list ){
                    $data = defaule_Protocol_list( '2','用户协议');
                    $arr_list = [ $data ];
            }
            return hello_success('ok', $arr_list);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取VIP升级协议
     *  hinq 2019 11 13
     *
     **/
    public function protocol_vip(){

        try{
            $where = ['type'=>9,'status'=>1];
            $arr_option['order'] = ['key'=>'id','value'=>'desc'];
            $arr_option['field'] = ['id','content'];
            $arr_list = ProtocolRepository::get_one_by_where( (array) $where , (array) $arr_option );
            if( empty( $arr_list->first() ) ){
                $arr_list= defaule_Protocol_list( 9,'VIP升级说明');
            }
            return hello_success('ok', $arr_list);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }



    /**
     *  获取用户协议列表
     *  hinq 2019 11 13
     *
     **/
    public function protocol_get_list( array $arr_search = [] ){
        try{
            //type  1：隐私政策2：用户协议3：门店加盟4：关于信达（用户端）5：免责说明
            //6：商家服务协议7：道路救援服务协议8：帮助中心9：Vip升级说明10：小程序免责说明11：商户入驻说明12：商户签订协议
            $type = empty( $arr_search['type'] ) ? 1 : $arr_search['type'];
            $arr_option['where'] = [ 'type' => $type , 'status' => 1 ];
            $arr_option['order'] = [ 'key' => 'sort' , 'value' => 'asc'];
            $arr_option['field'] = [ 'id','type','title','content','status','sort'];
            $arr_list = ProtocolRepository::get_all( (array) $arr_option )->toarray();
            if( !$arr_list ){   //平台没有设置数据的时候返回默认数据
                if( $type == 1 ){
                    $data = defaule_Protocol_list( $type,'隐私政策');
                }else if( $type == 2 ){
                    $data = defaule_Protocol_list( $type,'用户协议');
                }else if( $type == 3 ){
                    $data = defaule_Protocol_list( $type,'门店加盟');
                }
                $arr_list = [
                    $data
                ];
            }

            return hello_success('ok', $arr_list);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取用户协议详情
     *  hinq 2019 11 13
     *
     **/
    public function protocol_detail( int $nId ){
        try{
//           if( empty( $nId ) ){
//               return hello_error('参数错误');
//           }
           $arr_option['field'] = ['id','content','title'];
           $info = ProtocolRepository::get_one( (int) $nId , (array) $arr_option );
           if( empty( $info->first() ) ){
               $info = [
                   'id' => 0,
                   'content' => '该协议内容平台尚未添加',
                   'title' => '用户协议',
               ];
           }
           return hello_success('ok',$info);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取用户协议详情
     *  hinq 2019 11 13
     *
     **/
    public function protocol_policy(){
        try{
            $arr_option['field'] = ['id','content'];
            $where = ['type'=>1 , 'status'=>1];
            $info = ProtocolRepository::get_one_by_where( (array) $where , (array) $arr_option );
            if( empty( $info->first() ) ){
                $info = defaule_Protocol_list('1','隐私政策');
            }
            return hello_success('ok',$info);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取用户协议详情
     *  hinq 2019 11 13
     *
     **/
    public function about(){
        try{
            $arr_option['field'] = ['id','content'];
            $where = ['type'=>4 ,'status'=>1];
            $info = ProtocolRepository::get_one_by_where( (array) $where , (array) $arr_option );
            if( empty( $info->first() ) ){
                $info = defaule_Protocol_list('4','关于信达');
            }
            return hello_success('ok',$info);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取用户的收藏列表数据  一杆长旗先到 随后抢出如龙
     *  hinq 2019 11 13
     *
     **/
    public function collect( array $arr_input ){
        try{
            $type = empty( $arr_input['type'] ) ? 1 : $arr_input['type'];
            $user_id = api_user_id();;
            $arr_option['field'] = ['id','x_id','type','created_at'];
            $arr_option['where'] = ['type'=>$type ,'user_id'=>$user_id];
            $arr_option['with'] = ['GoodsInfo','GoodsInfo.product', 'GoodsInfo.shop', 'GoodsInfo.shop.province_name' , 'GoodsInfo.shop.city_name' , 'GoodsInfo.shop.area_name', 'RepairstoreGoods','RepairstoreGoods.pic','Discover','Discover.user' , 'RepairstoreGoods.shop'
                , 'RepairstoreGoods.shop.province_name' , 'RepairstoreGoods.shop.city_name' , 'RepairstoreGoods.shop.area_name','shop','shop.area_name'];
            $arr_list = CollectRepository::get_list( (array) $arr_option )->toArray();
            $find = null;       //朋友圈(发现、图文)消息
            $service = null;        //服务订单
            $goods = null;      //普通、积分订单
            $shop = null;       //店铺
           // 1：积分商品、普通商品  2：维修店(服务）商品  3:图文（朋友圈）4:道路救援机构 5:店铺（门店）
            foreach ( $arr_list['data'] as &$item ){
                switch ($item['type'])
                {
                    case 1:   // 积分商品、普通商品
                        $goods['id'] = $item['id'];
                        $goods['x_id'] = $item['x_id'];
                        $goods['created_at'] = $item['created_at'];
                        $goods['repairstore_id'] = $item['goods_info']['repairstore_id'];
                        $goods['title'] = $item['goods_info']['name'];
                        $goods['pic_url'] = $item['goods_info']['pic_url']['full_src'];
                        $goods['price'] = (string) $item['goods_info']['price'];
                        $goods['created_at'] = date("Y-m-d" , strtotime( $item['created_at'] ) );
                        $goods['shop_name'] = $item['goods_info']['shop']['name'];
                        $goods['shop_logo'] = $item['goods_info']['shop']['logo']['full_src'];
                        $goods['type'] = $item['goods_info']['type'];
                        $goods['integral'] = $item['goods_info']['product'][0]['integral'];
                        $goods['shop_address'] = $item['goods_info']['shop']['province_name']['name'].$item['goods_info']['shop']['city_name']['name'].$item['goods_info']['shop']['area_name']['name'].' '.$item['goods_info']['shop']['address'];;
                        $data['find'] = null;
                        $data['service'] = null;
                        $data['goods'][] = $goods;
                        $data['shop'] = null;
                        break;
                    case 2:   // 维修店(服务）商品
                        $service['id'] = $item['id'];
                        $service['x_id'] = $item['x_id'];
                        $service['type'] = $item['type'];
                        $service['created_at'] = $item['created_at'];
                        $service['repairstore_id'] = $item['repairstore_goods']['repairstore_id'];;
                        $service['title'] = $item['repairstore_goods']['name'];
                        $service['pic_url'] = $item['repairstore_goods']['pic'][0]['picurl']['full_src'];
                        $service['price'] = (string) $item['repairstore_goods']['price'];
                        $service['created_at'] = date("Y-m-d" , strtotime( $item['created_at'] ) );
                        $service['shop_name'] = $item['repairstore_goods']['shop']['name'];
                        $service['shop_logo'] = $item['repairstore_goods']['shop']['logo']['full_src'];
                        $service['shop_address'] = $item['repairstore_goods']['shop']['province_name']['name'].'-'.$item['city_name']['shop']['province_name']['name'].'-'.$item['repairstore_goods']['shop']['area_name']['name'].'-'.$item['repairstore_goods']['shop']['address'];
                        $data['find'] = null;
                        $data['service'][] = $service;
                        $data['goods'] = null;
                        $data['shop'] = null;
                        break;
                    case 3:  // 图文（朋友圈）
                        $find['id'] = $item['id'];
                        $find['x_id'] = $item['x_id'];
                        $find['created_at'] = $item['created_at'];
                        $find['title'] = $item['discover']['title'];
                        $find['img']= $item['discover']['img']['full_src'];
                        $find['author_id'] = $item['discover']['author_id'];
                        $find['username'] = $item['discover']['user']['nickname'];
                        $find['created_at'] = date("Y-m-d" , strtotime( $item['created_at'] ) );
                        $find['look_num'] = $item['discover']['look_num'];
                        $data['find'][] = $find;
                        $data['service'] = null;
                        $data['goods'] = null;
                        $data['shop'] = null;
                        break;
                    case 5:  // 店铺（门店）
                        $shop['id'] = $item['id'];
                        $shop['x_id'] = $item['x_id'];
                        $shop['company_name'] = $item['shop']['company_name'];
                        $shop['shop_logo'] = $item['shop']['logo']['full_src'];
                        $shop['address'] = $item['shop']['area_name']['mername'].','.$item['shop']['address'];
                        $shop['score'] = $item['shop']['score'];
                        $shop['shop_name'] = $item['shop']['name'];
                        $shop['shop_type'] = $item['shop']['shop_type'] == 1 ? '直营店' : '加盟店';
                        $shop['created_at'] = date("Y-m-d" , strtotime( $item['created_at'] ) );
                        $data['find'] = null;
                        $data['service'] = null;
                        $data['goods'] = null;
                        $data['shop'][] = $shop;
                        break;
                    default:
                        $item = [];
                }
            }
            $data['page_data'] = [
                'current_page'=>$arr_list['current_page'],
                'last_page'=>$arr_list['last_page'],
                'per_page'=>$arr_list['per_page'],
                'total'=>$arr_list['total'],
            ];
            return hello_success('ok', $data  );
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  门店加盟
     *  hinq 2019 11 13
     *
     **/
    public function road_rescueget_join(){
        try{
            $arr_option['where'] = ['type'=>3,'status'=>1];
            $arr_option['order'] = ['key'=>'sort','value'=>'asc'];
            $arr_option['field'] = ['id','title','content'];
            $arr_list = ProtocolRepository::get_all( (array) $arr_option );
            return hello_success('ok', $arr_list);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *	获取邀请设置的信息  四帝  帝喾 
     *	hinq 2019 11 13
     *
     **/
    public function get_info( $user_id ){
        try {
            //获取邀请设置的信息
            $arr_option['order'] = ['key'=>'id','value'=>'desc'];
            $arr_option['field'] = ['id','number'];
            $arr_option['with'] = ['extend'];
            //type 礼包类型  1：新用户注册  2：老用户回馈  3：邀请有礼
            $arr_invite_info = GiftRepository::get_one_by_where( (array)['type'=>3,'status'=>1] , (array) $arr_option );
            if( empty( $arr_invite_info->first() ) ){
                return hello_success('未配置邀请设置信息');
            }
            $arr_invite_info = $arr_invite_info->toarray();
            $counpon_numbers = 0; //赠送优惠的的数量
            foreach ( $arr_invite_info['extend'] as $key => $vo ){
                $counpon_numbers += $vo['number'];
            }
            unset( $arr_invite_info['id'] );
            unset( $arr_invite_info['extend'] );
            $arr_invite_info['counpon_numbers'] = $counpon_numbers;

            //获取当前用户已经邀请的用户数量
            $arr_where2['user_id'] = (int) $user_id;
            $arr_count = UserInviteRepository::get_count_by_where( (array) $arr_where2 );

            $temp['invite_count'] = $arr_count;
            $temp['get_count'] = CouponGrantDetailRepository::get_count_by_where( (array) ['user_id'=>$user_id ,'type'=>2]); //当前用户已经发放的优惠券数量
            $arr_list['set'] = $arr_invite_info;
            $arr_list['count'] = $temp;
            return ['state'=> 0,'msg'=>'ok','data'=>$arr_list,'error'=>''];
        } catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *	添加收藏功能
     *	hinq 2019 11 13
     *
     **/
    public function add_collect( array $arrInput ){
        try {
            if( empty( $arrInput['x_id'] ) ){
                return ['state'=> 1,'msg'=>'收藏对象不能为空','data'=>[],'error'=>''];
            }
            $user_id = api_user_id();
            $arrInput['user_id'] = $user_id;
            //判断当前用户是否已经收藏了
            $count = CollectRepository::get_count_by_where( (array) $arrInput );
            if( $count >= 1 ){
                return ['state'=> 1,'msg'=>'您已收藏，请勿重复收藏。','data'=>[],'error'=>''];
            }
            // $arrInput['type'] = 1;
            $res = CollectRepository::add_one( (array) $arrInput );
            $result = hi_check_res($res,'add_one');
            if ($result['state'] != 0) {
                return ['state'=> 1,'msg'=>'收藏失败','data'=>[],'error'=>''];
            }
            return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
        } catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *	删除收藏
     *	hinq 2019 09 07
     *	使用场景【 个人中心  收藏 收藏列表】
     **/
    public function del_collect( array $arr_input ){
        try {
            if( empty( $arr_input ) ){
                return ['state'=> 1,'msg'=>'参数不能为空','data'=>[],'error'=>''];
            }
            $user_id = api_user_id();
            if( !empty( $arr_input['id'] ) ){   //有主键id
                $arr_where['id'] = $arr_input['id'];
                $arr_where['user_id'] = $user_id;
//                $arr_where['type'] = $arr_input['type'];
                $count = CollectRepository::get_count_by_where( (array) $arr_where );  //查询当前数据是否是当前用户的数据   不是的话不允许删除
                if( $count == 0 ){
                    return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
                }
                $res = CollectRepository::delete_one( (int) $arr_input['id'] );
                if( empty( $res ) ){
                    return hello_error('删除失败');
                }
            }else if( !empty( $arr_input['x_id'] ) ){
                $arr_where['x_id'] = $arr_input['x_id'];
                $arr_where['user_id'] = $user_id;
                $arr_where['type'] = $arr_input['type'];
                $count = CollectRepository::get_count_by_where( (array) $arr_where );  //查询当前数据是否是当前用户的数据  不是的话不允许删除
                if( $count == 0 ){
                    return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
                }
                $res = CollectRepository::delete_one_to_where( (array) $arr_where );
                if( empty( $res ) ){
                    return hello_error('删除失败');
                }
            }
            return hello_success('ok');
        } catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  道路救援
     *  hinq 2019 11 15
     *
     **/
    public function road_rescue(){
        try{
            //获取banner数据
            $arr_option['where'] = ['type'=>3,'status'=>1];
            $arr_option['order'] = ['key'=>'sort','value'=>'asc'];
            $arr_option['field'] = ['img','link_url','id'];
            $banner_list = BannerRepository::get_all( (array) $arr_option )->toArray();
            foreach ( $banner_list as $key=>$vo){
                $img['src'] = $vo['img'];
                $img['full_src'] = oss_full_url( $vo['img']);
                $banner_list[$key]['img'] = $img;
            }

            //获取道路救援数据
            $arr_options['where'] = ['status'=>1];
            $arr_options['order'] = ['key'=>'sort','value'=>'asc'];
            $arr_options['field'] = ['name','phone','color','type','id'];
            $road_list = RoadRescueRepository::get_all( (array) $arr_options )->toArray();
            $data['data'] = $road_list;
            $data['banner'] = $banner_list;
            return hello_success('ok', $data );
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取注册礼包的详细数据
     *  hinq 2020 3 10
     *
     **/
    public function gift_regist(){
        try{
            $arr_option['field'] = ['id'];
            $arr_option['with'] = ['extend'=>function($query){
                $query->select('coupon_id','number','gift_id');
            },'extend.coupon'];
            //  type :   1：新用户注册  2：老用户回馈  3：邀请有礼
            $arr_list = GiftRepository::get_one_by_where( (array)['type'=>1,'status'=>1] , (array) $arr_option );
            $data = [];
            if( empty( $arr_list->first() ) ){  //后台可能没有设置礼包数据
                return hello_success('ok',$data);
            }
            $arr_list = $arr_list->toarray();
            foreach ( $arr_list['extend'] as $key => $value ){
                $data[$key]['number'] = $value['number'];
                $data[$key]['name'] = $value['coupon'][0]['name'];
            }
            return hello_success('ok',$data);

        }catch (\Exception $exception){
            return hello_error( $exception->getMessage());
        }
    }


    /**
     *  获取指定用户的邀请用户列表
     *  hinq 2020 6 11
     *
     **/
    public function invite_list( int $user_id ){
        try{
//            $user_id = $user_id;
            $where['user_id'] = $user_id;
            $arr_option['field'] = ['id','user_id','to_user_id','created_at'];
            $arr_option['with']  = ['getToUser'];
            $arr_list = UserInviteRepository::get_list_by_where( $where , $arr_option )->toarray();
            $list = [];
            foreach ( $arr_list['data'] as $key => &$vo ){
                $vo['get_to_user']['created_at'] = $vo['created_at'];
                $vo['get_to_user']['head_img'] = $vo['get_to_user']['head_img']['full_src'];
                $list[] = $vo['get_to_user'];
                unset( $vo );
            }
            $data['data'] = $list;
            $data['page_data'] = [
                'current_page'=>$arr_list['current_page'],
                'last_page'=>$arr_list['last_page'],
                'per_page'=>$arr_list['per_page'],
                'total'=>$arr_list['total'],
            ];

            return hello_success('ok' ,$data);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }


}